package com.yu.dv.service;

import com.yu.dv.strategy.StrategyFactoryBuilder;
import com.yu.dv.strategy.metadata.MetadataStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;

@Slf4j
@Service
public class DatabaseMetadataService {

    private final DataSource dataSource;

    public DatabaseMetadataService(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public String getDatabaseSchemaAsText() {
        try (Connection connection = dataSource.getConnection()) {
            String databaseProductName = connection.getMetaData().getDatabaseProductName();
            MetadataStrategy strategy = StrategyFactoryBuilder.getMetadataStrategyFactory().getStrategy(databaseProductName);
            return strategy.getDatabaseSchemaAsText(connection);
        } catch (Exception e) {
            return "无法获取数据库结构: " + e.getMessage();
        }
    }

    public String getSimplifiedDatabaseSchema() {
        try (Connection connection = dataSource.getConnection()) {
            String databaseProductName = connection.getMetaData().getDatabaseProductName();
            MetadataStrategy strategy = StrategyFactoryBuilder.getMetadataStrategyFactory().getStrategy(databaseProductName);
            return strategy.getSimplifiedDatabaseSchema(connection);
        } catch (Exception e) {
            return "无法获取数据库结构: " + e.getMessage();
        }
    }

    public String getDatabaseProductName() {
        try (Connection connection = dataSource.getConnection()){
            return connection.getMetaData().getDatabaseProductName();
        }catch (Exception e){
            return "无法获取数据库产品名称: " + e.getMessage();
        }
    }
}